package com.service.gmall.product.init;

import com.service.gmall.common.constant.SysRedisConst;
import com.service.gmall.product.service.SkuInfoService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author alpha
 * @className: SkuIdBloomInitService
 * @Description
 */
@Slf4j
@Service
public class SkuIdBloomInitService {
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    RedissonClient redissonClient;

    /**
     * 初始化布隆过滤器操作
     */
    @PostConstruct//项目运行就运行
    public void initSkuBloom(){
        log.info("布隆初始化正在进行....");
        //1.查询出所有的skuId
        List<Long> allSkuId = skuInfoService.getAllSkuId();
        //2.把所有的id初始化到布隆过滤器中
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(SysRedisConst.BLOOM_SKUID);

        boolean exists = bloomFilter.isExists();
        if (!exists){
            //3.尝试初始化
            bloomFilter.tryInit(5000000,0.00001);
        }

        //4.把所有的商品添加到布隆中。
        for (Long skuId : allSkuId) {
            bloomFilter.add(skuId);
        }
        log.info("布隆初始化完成....，总计添加了 {} 条数据",allSkuId.size());
    }
}
